package com.c4p.im.server;


import cn.hutool.extra.spring.SpringUtil;
import com.c4p.config.WebSocketProperties;
import com.c4p.im.handler.MessageHandler;
import com.c4p.im.handler.UserInfoExactHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IMServer {


    public void start(){
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup work = new NioEventLoopGroup();


        try{
            WebSocketProperties properties = SpringUtil.getBean(WebSocketProperties.class);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, work)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast("http", new HttpServerCodec());
                        ch.pipeline().addLast(new ChunkedWriteHandler());
                        ch.pipeline().addLast(new HttpObjectAggregator(100 * 1024 * 1024));
                        ch.pipeline().addLast(new UserInfoExactHandler());
                        ch.pipeline().addLast("websocket",
                                new WebSocketServerProtocolHandler(properties.getPath(), true));
                        ch.pipeline().addLast(new MessageHandler());


                    }
                });

            Channel channel = bootstrap.bind(properties.getPort()).sync().channel();

            log.info("Netty websocket start port:{}, path:{}", properties.getPort(), properties.getPath());

            channel.closeFuture().sync();

        }catch (Exception e){

            log.error("start error");
        }finally {
            work.shutdownGracefully();
            boss.shutdownGracefully();
        }

    }
}
